/**
 * Created by imac13 on 18/12/22.
 */
import React, { Component, Fragment} from 'react';
import TodoItem from './TodoItem'
import Action from './Action'
import axios from 'axios'
import './style.css'
class TodoList extends Component {
    constructor (props) {
        super(props)
        this.state = {
            inputValue: '',
            list: []
        }
        this.handleInput = this.handleInput.bind(this)
        this.addList = this.addList.bind(this)
        this.deleItem = this.deleItem.bind(this)
    }
    componentDidMount () {
        axios.get('/api/todolist').then((res)=>{
            this.setState(()=>{
                return {
                    list: [...res.data]
                }
            })
        }).catch(()=>{
            alert('error')
        })
    }
    render() {
        return (
            <Fragment>
                <div className="father">
                    <label htmlFor="insert">请输入内容：</label>
                    <input
                        className="inputText"
                        id="insert" type="text"
                        onChange={this.handleInput}
                        value={this.state.inputValue}
                        // ref={(input) => {this.input = input}}
                    />
                    <button onClick={this.addList}>添加</button>
                </div>
                <ul>
                    {this.getItem()}
                </ul>
                <Action />
            </Fragment>
        );
    }
    getItem () {
        return this.state.list.map((item,index) =>{
            return (
                <TodoItem
                    key = {index}
                    content = {item}
                    index = {index}
                    deleItem = {this.deleItem}
                />
            )
        })
    }
    handleInput (e) {
       const value = e.target.value
        this.setState(() => ({
            inputValue: value
        }) )
    }
    addList () {
        this.setState((prevState) => {
            let List = [...prevState.list]
            List = [...prevState.list,prevState.inputValue]
            return{
                list: List,
                inputValue: ''
            }
        })
    }
    deleItem (index) {
        this.setState((prevState) => {
            const list = [...prevState.list]
            list.splice(index,1)
            return {list}
        })
    }
}

export default TodoList;
